package cn.com.callback

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;
import org.json.JSONObject;
import org.json.JSONException;
import com.alibaba.fastjson.JSON;

/**
 *
 * @Title: api_SZWaterDB
 * @Description: 功能介绍：定时调用此接口，将documentout中符合条件的短信调度短信平台接口
 * @author: chieh
 * @date 2021-11-22 15:28:00
 *
 */

public class api_SZWaterDB implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(api_SZWaterDB.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        try {
            def SMSCount = 0;
            def message;
            def outdata;
            def msg;
            def updateDocumentoutSQL;

            log.debug("发送短信开始执行------------------------------");
			String selectDocumentoutSQL = '''Select Top 100 Documentout_Guid,
												   Documentto,
												   Replace(Replace(Replace(Documentpath, '【深圳水务集团】', ''), '【', '['), '】', ']') As Documentpath,
												   Convert(Varchar(100), Expectedstartdate, 20) As Expectedstartdate,
												   Stringfield1,
												   Sms_Guid,
												   Case
													 When Stringfield1 = '人工短信' Then
													  1
													 When Stringfield1 = '工单' Then
													  2
													 When Stringfield1 = '通讯录短信' Then
													  3
													 When Stringfield1 = '智慧停水发送' Then
													  4
													 When Stringfield1 = '人工批次发送' Then
													  4
												   End As Priority,
												   Createdby
											  From Documentout With(Nolock)
											 Where Expectedstartdate <= Getdate()
											   And Passflag Is Null
											   And Doctype = '3'
											   And Isnumeric(Documentto) = 1
											 Order By Priority, Createddate''';

            List selectDocumentoutList = eliteBean.chaxun_sql(selectDocumentoutSQL, "dataSource");
            int ListNum = selectDocumentoutList.size();
            log.debug("待发送短信数量ListNum=" + ListNum);

            if (ListNum > 0) {
                for (int i = 0; i < ListNum; i++) {
                    Map selectDocumentoutSQLMap = selectDocumentoutList.get(i);

					String documentout_guid = selectDocumentoutSQLMap.get("Documentout_Guid");
					String documentto = selectDocumentoutSQLMap.get("Documentto");//手机号码
					String DOCUMENTPATH = selectDocumentoutSQLMap.get("Documentpath");//短信内容
					String EXPECTEDSTARTDATE = selectDocumentoutSQLMap.get("Expectedstartdate");//发送时间
					String stringfield1 = selectDocumentoutSQLMap.get("Stringfield1");//短信类型批次名称
					String sms_guid = selectDocumentoutSQLMap.get("Sms_Guid");//批量短信导入批次号
					String CREATEDBY = selectDocumentoutSQLMap.get("Createdby");//短信创建人

                    //获取短信部门
					String busdept = "";//部门id
					List selectbusdeptresult = eliteBean.chaxun_sql("select DISTINCT  ra.busdept from staff s LEFT JOIN RolegroupArea rga ON s.DEFAULTROLEGROUP = rga.Group_id LEFT JOIN Group_Area ra ON rga.Area_guid = ra.Area_guid where s.staff_id='" + CREATEDBY + "'", "dataSource");
                    if (selectbusdeptresult.size() > 0) {
                        busdept = selectbusdeptresult.get(0).get("busdept");
                    }
                    log.debug("发送短信类型busdept：" + busdept);

                    outdata = sendsms(documentto, DOCUMENTPATH, EXPECTEDSTARTDATE, stringfield1, busdept);
                    log.debug("发送短信结果：" + outdata);

                    //解析返回信息
                    JSONObject jsonObject = new JSONObject(outdata);
                    String statusCode = GetJV(jsonObject, "statusCode");
                    String resultCode = GetJV(jsonObject, "resultCode");

                    if (statusCode == "0") {
                        SMSCount++;
                        if (stringfield1 != '人工批次发送') {
                            updateDocumentoutSQL = "Update Documentout Set Passflag = '1',resultCode='" + resultCode + "', Lasttrydatetime = Getdate(), Modifiedby = 'SELITE', Modifieddate = Getdate(), Faildescription = '1/1' Where Documentout_Guid = '" + documentout_guid + "'";
                        } else {
                            updateDocumentoutSQL = "Update Documentout Set Passflag = '1',resultCode='" + resultCode + "', Lasttrydatetime = Getdate(), Modifiedby = 'SELITE', Modifieddate = Getdate(), Faildescription = '1' Where Documentout_Guid = '" + documentout_guid + "'";
                        }
                        log.debug("短信平台回写Documentout表SQL:" + updateDocumentoutSQL);

                        def updateDocumentouFlag = eliteBean.update(updateDocumentoutSQL, "dataSource");
                        log.debug("短信平台回写Documentout表SQL执行结果:" + updateDocumentouFlag);
                    } else {
                        eliteBean.update("update Documentout set Passflag = '1',Lasttrydatetime = Getdate(), Modifiedby = 'SELITE', Modifieddate = Getdate() Where Documentout_Guid = '" + documentout_guid + "'", "dataSource");
                        log.debug("写入短信平台接口失败！");
                    }

                }
                msg = "当前批次共有" + ListNum + "条数据，成功插入" + SMSCount + "条！";
                log.debug("当前需要发送短信的数据处理结果:" + msg);

                //智慧停水短信 发送成功标识更新
				String waterOffSmsbatchSQL = '''Update Wateroffsmsbatch
												   Set Status = 2, Finishdate = Getdate()
												 Where Sms_Guid In (Select Distinct Sms_Guid
																	  From Documentout With(Nolock)
																	 Where Stringfield1 = '智慧停水发送\'
																	   And Passflag = '1\'
																	   And Expectedstartdate > Getdate() - 1
																	 Group By Sms_Guid)''';
                log.debug("智慧停水短信发送状态waterOffSmsbatch表SQL:" + waterOffSmsbatchSQL);

                int waterOffSmsbatchFlag = eliteBean.update(waterOffSmsbatchSQL, "dataSource");
                log.debug("智慧停水短信发送状态更新waterOffSmsbatch表SQL执行结果:" + waterOffSmsbatchFlag);

                message = "{\"message\":\"" + msg + "\"}";
            } else {
                message = '{"message":"当前批次下没有需要发送短信的数据"}';
            }

        } catch (Exception e) {
            log.error("api_SZWaterDB异常信息：", e);
        }
    }

    //短信发送接口
    public static String sendsms(String mobile, String content, String Expectedstartdate, String bustype, String busdept) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = "http://138.0.0.53:8083/sms/api/send";
            log.debug("doURL:" + doURL);

            String userId = "CRMAPI";
            String password = "ghbsmsapi";
            String apikey = "89a47d";
            String signafter = "";
            String sign = "";

            if (bustype == '人工短信') {//crmUserSMS CRM用户短信
                bustype = 'crmUserSMS';
            } else if (bustype == '工单' || bustype == '工单催单短信') {//crmGDTZ crm工单短信  工单催单短信
                bustype = 'crmGDTZ';
            } else if (bustype == '通讯录短信') {//crmTXL crm通讯录短信  
                bustype = 'crmTXL';
            } else if (bustype == '智慧停水发送') {//crmTSTZ 停水通知
                bustype = 'crmTSTZ';
            } else if (bustype == '人工批次发送') {//crmBatch crm人工批量短信
                bustype = 'crmBatch';
            }

            //加盐pwd= md5(userId + 明文密码 + 盐
            signafter = userId + password + apikey;
            log.debug("1加密前:" + signafter);
            signafter = Util.getMD5Str(signafter);
            log.debug("1加密后:" + signafter);
            //MD5(userId+pwd)
            signafter = userId + signafter;
            log.debug("2加密前:" + signafter);
            sign = Util.getMD5Str(signafter);
            log.debug("2加密后:" + sign);

            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");

            Map<String, String> messageMap = new HashMap<>();
            messageMap.put("userId", userId);
            messageMap.put("mobile", mobile);
            messageMap.put("content", content);
            messageMap.put("signature", sign);
            messageMap.put("busdept", busdept);
            messageMap.put("bustype", bustype);
            String injson = JSON.toJSONString(messageMap);
            log.debug(injson);

			String getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);

            reJson = getResult;

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"statusCode\":\"-1\",\"resultMsg\":\"短信发送接口异常\",\"resultCode\":\"\"}";
        }

        return reJson;
    }
    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}